package com.wisdom.core.netty.handler.client;

import com.alibaba.fastjson.JSON;
import com.wisdom.core.data.RpcRequest;
import com.wisdom.core.exception.RpcException;
import com.wisdom.core.util.ProtostuffUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @description: <将RpcRequest对象编码为字节数据>
 * @author: Leo
 * @date: 2021-08-23 18:59
 */
@Slf4j
public class RpcRequestEncoder extends MessageToMessageEncoder<RpcRequest> {

    @Override
    protected void encode(ChannelHandlerContext ctx, RpcRequest rpcRequest, List<Object> out) {
       try {
           log.info("client send msg, msg is {}", JSON.toJSONString(rpcRequest));
           byte[] bytes = ProtostuffUtil.serialize(rpcRequest);
           ByteBuf buf = ctx.alloc().buffer(bytes.length);
           buf.writeBytes(bytes);
           out.add(buf);
       }catch (Exception e){
           log.error("RpcRequestEncoder encode RpcRequest error, msg is {}",e.getMessage());
           throw new RpcException(e.getMessage(),e);
       }

    }
}
